import { useState, useEffect } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import CommonTable from '@/components/CommonTable';
import IconFont from '@/components/IconFont';
import { Alert, Button, Popover } from 'antd';
import { Base64 } from 'js-base64';
import { getCurrentUser } from '@/utils/authority';
import { getEslistGroup, setEsListGroupDefault } from '../../services';
import styles from './index.module.less';

//子账号授权
const JuniorAccount = ({ handleCancel }) => {
  const iconType = { 8: 'icontaobao', 15: 'icondy' }; //icon类型
  const [juniorAccountList, setJuniorAccountList] = useState([]); //子账号数据列表
  const [loading, setLoading] = useState(true);
	const [open, setOpen] = useState(false);
  // const [existsAccess, setExistsAccess] = useState(false);  //是否存在未配置的
  useEffect(() => {
    getList();
		setOpen(true);
  }, []);

  const tableColumn = [
    {
      title: '子账号名称',
      dataIndex: 'nick',
      align: 'center',
      render: (text, record, index) => {
        return (
          <div className={record.isDefault ? styles.defaultStyle : ''}>
            {text}
          </div>
        );
      },
    },
    {
      title: 'erp授权状态',
      dataIndex: 'authorizationState',
      render: (text, record, index) => {
        return (
          <div className={record.isDefault ? styles.defaultStyle : ''}>
            {text == -1
              ? '淘宝授权信息读取失败'
              : text == 1
              ? '授权成功'
              : '未授权'}
          </div>
        );
      },
      align: 'center',
    },
    {
      title: '是否默认',
      dataIndex: 'isDefault',
      render: (text, record, index) => {
        return (
          <div className={record.isDefault ? styles.defaultStyle : ''}>
            {text == 1 ? '是' : '否'}
          </div>
        );
      },
      align: 'center',
    },
    {
      title: (
        <Popover
          content={
            <div style={{ width: '300px' }}>
              未配置：表示该子账号，未在淘宝平台的配置售后权限
            </div>
          }
        >
          <div>
            售后权限
            <IconFont type="iconwenhao1" />
          </div>
        </Popover>
      ),
      dataIndex: 'afterSalfConfigFinished',
      render: (text, record, index) => {
        return (
          <div className={record.isDefault ? styles.defaultStyle : ''}>
            {text == 1 ? '已配置' : '未配置'}
          </div>
        );
      },
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'isDefault',
      render: (text, record, index) => {
        return record.afterSalfConfigFinished == 0 ? (
          ''
        ) : record.authorizationState != 1 ? (
          <Button
            type="link"
            onClick={goAccess(record.subId, record.storeId)}
            style={{ fontSize: '13px' }}
          >
            去授权
          </Button>
        ) : record.isDefault ? (
          <Button
            type="link"
            onClick={setDefault(record.id, record.storeId)}
            style={{ color: '#0165D5' }}
          >
            取消默认
          </Button>
        ) : (
          <Button
            type="link"
            onClick={setDefault(record.id, record.storeId)}
            style={{ fontSize: '13px' }}
          >
            设为默认
          </Button>
        );
      },
      align: 'center',
    },
  ];
  //获取店铺子账号列表
  const getList = async () => {
    setLoading(true);
    const { success, data = [] } = await getEslistGroup({});
    setLoading(false);
    if (success) {
      const Jdata = data.map((item) => {
        item.ecSubuserList.map((items) => {
          // !existsAccess &&
          //   items.afterSalfConfigFinished == 1 &&
          //   setExistsAccess(true);
          items.storeId = item.storeId;
          return item;
        });
        return item;
      });
      setJuniorAccountList(Jdata);
    }
  };
  //设置默认子账号
  const setDefault = (id, storeId) => {
    return async () => {
      setLoading(true);
      const { success, data = [] } = await setEsListGroupDefault({
        id,
        storeId,
      });
      if (success) {
        getList();
      }
      setLoading(false);
    };
  };
  const taobao = {
    id: 1,
    src: 'https://imgniu.zhaojiafang.com/front-web/ERP/tb.png',
    name: '淘宝',
    path: `https://oauth.taobao.com/authorize?response_type=code&client_id=23416550&redirect_uri=http://tb-api.zhaojiafang.com/TopSdk.php&state=${AUTHORIZE_URL}/taobao/callback-callback-`,
  };

  const goAccess = (subId, storeId) => {
    //淘宝
    return () => {
      const url = window.location.href;
      const obj = {
        url,
        userName: getCurrentUser().account,
        uuid: getCurrentUser().uuid,
        storeId: storeId,
        subTaobaoUserId: subId,
      };
      let path = taobao.path;

      const src = `${path}${encodeURIComponent(
        Base64.encode(JSON.stringify(obj))
      )}`;
      window.location.href = src;
    };
  };

	const onCancel = () => {
		setOpen(false);
	}

	const afterClose = () => {
		handleCancel();
	}

  return (
    <CommonModal
      title="子账号授权"
			open={open}
      width="600px"
      onCancel={onCancel}
			afterClose={afterClose}
      footer={
          <Button key="close" onClick={onCancel}>
            关闭
          </Button>
      }
    >
      <Alert
        style={{ marginBottom: 12 }}
        message={
          <div>
            淘宝处理退款需要<span style={{ color: '#D9001B' }}>子账号授权</span>
            才能操作
          </div>
        }
        type="warning"
        showIcon
        closable
      />
      {juniorAccountList.map((item) => {
        return (
          <div className={styles.warp_group} key={item.storeId}>
            <div className={styles.group_header}>
              <div className="group_img">
                <IconFont
                  type={iconType[item.type]}
                  style={{ fontSize: '20px', marginRight: '10px' }}
                />
              </div>
              <div className="group_title">{item.storeName}</div>
            </div>
            <div className={styles.groupTable}>
              {item.ecSubuserList.length > 0 ? (
                <CommonTable
                  columns={tableColumn}
                  data={item.ecSubuserList}
                  scroll={{
                    y: 150,
                  }}
                />
              ) : (
                <div style={{ marginLeft: '10px' }}> 该店铺无子账号</div>
              )}
            </div>
          </div>
        );
      })}
      <div style={{ textAlign: 'center' }}>
        {juniorAccountList.length < 1 && '暂无数据'}
      </div>

      {loading && <CommonLoading loading={loading} />}
    </CommonModal>
  );
};

export default JuniorAccount;
